﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using lruc.Model;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace lruc.Controllers
{
    public class ProjectController : BaseController
    {
        public ProjectController(IFreeSql fsql) : base(fsql) { }

        [HttpGet]
        public async Task<IDictionary<string, Object>> List() {
            List<Project> projects = await _fsql.Select<Project>().ToListAsync();
            JArray data = new JArray();
            foreach (Project project in projects)
            {
                JObject joProject = JObject.FromObject(project);
                joProject.Add("jodxfx", JObject.Parse(project.DxfxJson));
                joProject.Add("jotimefx", JObject.Parse(project.TimefxJson));
                joProject.Add("jocostfx", JObject.Parse(project.CostfxJson));
                joProject.Add("jomodelzr", JObject.Parse(project.ModelzrJson));
                joProject.Add("joschemegh", JObject.Parse(project.SchemeghJson));
                data.Add(joProject);
            }
            return RenderJson(data: data);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Save([FromForm] Project project)
        {
            long id = await _fsql.Insert(project).ExecuteIdentityAsync();
            project.Id = id;
            return RenderJson(data: project);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Delete([FromForm] long id)
        {
            int affrows = await _fsql.Delete<Project>().Where(p => p.Id == id).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpPost]
        public async Task<IDictionary<string, Object>> Update([FromForm] Project project)
        {
            int affrows = await _fsql.Update<Project>().SetSourceIgnore(project, colval => colval == null).ExecuteAffrowsAsync();
            return RenderJson(data: affrows);
        }

        [HttpGet]
        public async Task<IDictionary<string, Object>> Show([FromQuery] long id)
        {
            Project project = await _fsql.Select<Project>().Where(p => p.Id == id).ToOneAsync();

            JObject data = JObject.FromObject(project);
            data.Add("jodxfx", JObject.Parse(project.DxfxJson));
            data.Add("jotimefx", JObject.Parse(project.TimefxJson));
            data.Add("jocostfx", JObject.Parse(project.CostfxJson));
            data.Add("jomodelzr", JObject.Parse(project.ModelzrJson));
            data.Add("joschemegh", JObject.Parse(project.SchemeghJson));

            return RenderJson(data: data);
        }
    }
}
